//
//  CZMineViewController.m
//  nsj_iOS
//
//  Created by apple on 2016/12/30.
//  Copyright © 2016年 GCZ. All rights reserved.
//

#import "CZMineViewController.h"
#import "CZMessionCenterCartoonAlbumView.h"
#import "CZAddressManagerViewController.h"
#import "CZMultiSettingViewController.h"
#import "CZPayViewController.h"
#import "CZEnrollViewController.h"
#import "CZChangePWDViewController.h"
#import "CZChangePhoneViewController.h"
#import "CZBaseTabBarController.h"
#import "CZNavigationController.h"
#import "CZMessionCenterViewController.h"
#import "CCViewController.h"
#import "CZSettingsViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "CZUserLoginViewController.h"
#import "CZMineCell.h"
#import "CZUserModel.h"
#import "CZBindMoblieViewController.h"

#define ParallaxHeaderHeight (Main_Screen_Width * 0.7)
static NSString * const mine_cell = @"mine_cell";

@interface CZMineViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, copy) NSDictionary<NSString *, NSArray *> *titleDic;
@property (nonatomic, copy) NSDictionary<NSString* , NSArray *> *iconDic;

@property (strong, nonatomic) UIImageView *parallaxHeaderView;
@property (strong, nonatomic) MASConstraint *parallaxHeaderHeightConstraint;
@property (nonatomic, strong) UITableView *mineTableView;
@property (nonatomic, strong) CZUserModel *currentUser;
@property (nonatomic, strong) UILabel *nickNameLabel;


//OSSBucket *bucket;
//OSSFile *testFile;
@end

@implementation CZMineViewController

#pragma mark- Lazy 
- (NSDictionary *__nonnull)iconDic {
    if (!_iconDic) {
        _iconDic = @{
                      @"0" : @[@"my_icon_phone"],
                      @"1" : @[@"my_icon_nonmember", @"my_icon_nickname"],
                      @"2" : @[@"my_iocn_sex", @"my_icon_age", @"my_icon_qq", @"my_icon_guardian", @"my_icon_guarPhone", @"my_icon_address"],
                      @"3" : @[@"my_icon_money", @"my_icon_exp", @"my_icon_hoon"],
                      @"4" : @[@"my_icon_password"]
                      };
    }
    return _iconDic;
}

- (NSDictionary *__nonnull)titleDic {
    if (!_titleDic) {
        _titleDic = @{
                      @"0" : @[@"我的手机"],
                      @"1" : @[@"活动会员", @"昵称"],
                      @"2" : @[@"性别", @"年龄", @"QQ", @"监护人称呼", @"监护人电话", @"收货地址"],
                      @"3" : @[@"那币余额", @"成长值", @"勋位"],
                      @"4" : @[@"修改密码"]
                      };
    }
    return _titleDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人中心";
    self.navigationController.navigationController.navigationBar.alpha = 0;
    [self getUserData];
    self.automaticallyAdjustsScrollViewInsets = NO;
    UITableView *mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, self.view.size.height - 50) style:(UITableViewStyleGrouped)];
    [self.view addSubview:mineTableView];
    mineTableView.backgroundColor = [UIColor clearColor];
    mineTableView.delegate = self;
    mineTableView.dataSource = self;
    mineTableView.estimatedRowHeight = 50;
    mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [mineTableView registerNib:[UINib nibWithNibName:@"CZMineCell" bundle:nil] forCellReuseIdentifier:mine_cell];
    mineTableView.tableFooterView = [self setFootVeiew];
    UIView *headerView = [self setHeaderView];
    [mineTableView addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(mineTableView).offset(-100);
        make.width.equalTo(mineTableView);
        make.height.mas_equalTo(100);
        make.left.equalTo(mineTableView);
    }];
    mineTableView.contentOffset = CGPointMake(0, - ParallaxHeaderHeight);
    mineTableView.contentInset = UIEdgeInsetsMake(ParallaxHeaderHeight, 0, 0, 0);
    _mineTableView = mineTableView;
    [self setparallaxHeaderView];
}
- (void)viewWillAppear:(BOOL)animated {
//    [self setNaviBar];
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [self setNaviBar];
    self.tabBarController.tabBar.hidden = NO;
    [super viewDidAppear:animated];
    
    
}
- (void)tapAction {
    [self setIcon];
}

#pragma mark - 选择图片
- (void)setIcon {
    
    UIAlertController *alertController = [[UIAlertController alloc] init];
    UIAlertAction *photoLibraryAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
        UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypePhotoLibrary;
        imageaPicker.sourceType = sourceTypePhoto;
        imageaPicker.delegate = self;
        
        [self presentViewController:imageaPicker animated:YES completion:^{
            
        }];
    }];
    
    //访问受限
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"照相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertC addAction:action];
        } else if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
            UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypeCamera;
            imageaPicker.sourceType = sourceTypePhoto;
            imageaPicker.delegate = self;
            [self presentViewController:imageaPicker animated:YES completion:^{
                
            }];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:photoLibraryAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage* image = [[UIImage alloc] init];
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData * data = UIImageJPEGRepresentation(image, 1);
//    NSData *compressData = UIImageJPEGRepresentation(image, 0.1);

    CZNsjHelper *helper = [[CZNsjHelper alloc] init];
    @weakify(self);
    [helper uploadObjectSyncWithObjectKey:@"user_icon" fileData:data successStatus:nil errorStatus:@"头像上传失败" completion:^(NSString *urlString) {
        [weak_self updateUserIconWithURLString:urlString image:image];
    }];
    [SVProgressHUD showWithStatus:@"头像上传中"];
}


#pragma mark- tableViewHeaderView
- (UIView *)setHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 100)];
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(10, headerView.height - 85, 70, 70)];
//    iconView.image = [UIImage imageNamed:@"0ff41bd5ad6eddc444593de23fdbb6fd52663368.jpg"];
    iconView.layer.cornerRadius = iconView.frame.size.width / 2;
    iconView.layer.borderColor = [UIColor whiteColor].CGColor;
    iconView.layer.borderWidth = 1.5f;
    iconView.layer.shadowOpacity = 0.3;
    iconView.layer.shadowOffset = CGSizeMake(0, -1);
    iconView.layer.shadowRadius = 3;
    iconView.clipsToBounds = YES;
    iconView.layer.contentsScale = [UIScreen mainScreen].scale;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [iconView addGestureRecognizer:tap];
    iconView.userInteractionEnabled = YES;
    iconView.backgroundColor = [UIColor whiteColor];
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.height - 40, Main_Screen_Width, 40)];
    headerView.userInteractionEnabled = YES;
    _userIconImageView = iconView;
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]) {
        self.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
    }
    
    blackView.backgroundColor = mRGBACOLOR(0, 0, 0, 0.5);
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 200, 20)];
    userNameLabel.centerY = blackView.centerY;
    userNameLabel.textColor = [UIColor whiteColor];
//    userNameLabel.text = @"顾晨哲";
    _nickNameLabel = userNameLabel;
    if (_currentUser) {
        userNameLabel.text = _currentUser.nickname;
    }
    [headerView addSubview:blackView];
    [headerView addSubview:iconView];
    [headerView addSubview:userNameLabel];
    return headerView;
}

- (UIView *)setFootVeiew {
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 130)];
    footView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    UIButton *contactBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [footView addSubview:contactBtn];
    contactBtn.layer.cornerRadius = 5;
    contactBtn.clipsToBounds = YES;
    contactBtn.backgroundColor = mRGBColor(57, 204, 184);
    [contactBtn setTitle:@"设置" forState:(UIControlStateNormal)];
    [contactBtn addTarget:self action:@selector(settings) forControlEvents:(UIControlEventTouchUpInside)];
    contactBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    contactBtn.tintColor = [UIColor whiteColor];
    
    UIButton *logOutBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [footView addSubview:logOutBtn];
    logOutBtn.layer.cornerRadius = 5;
    logOutBtn.clipsToBounds = YES;
    logOutBtn.backgroundColor = mRGBColor(255, 105, 177);
    [logOutBtn setTitle:@"退出登录" forState:(UIControlStateNormal)];
    logOutBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    logOutBtn.tintColor = [UIColor whiteColor];
    [logOutBtn addTarget:self action:@selector(unbind) forControlEvents:(UIControlEventTouchUpInside)];
    [logOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(footView).offset(-20);
        make.height.equalTo(@40);
        make.left.equalTo(footView).offset(10);
        make.right.equalTo(footView).offset(-10);
    }];
    [contactBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(logOutBtn.mas_top).offset(-10);
        make.height.equalTo(@40);
        make.left.equalTo(footView).offset(10);
        make.right.equalTo(footView).offset(-10);
    }];

    return footView;
}

- (void)settings {
    CZSettingsViewController *settingVC = [[CZSettingsViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
}

- (void)unbind {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-info/get-info",APP_HOST];
    [SVProgressHUD showWithStatus:@"正在退出..."];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]} success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"退出成功"];
            [self logOut];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误 退出失败"];
    }];
    
}

- (void)logOut {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_Logo];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_Phone];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_Token];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_Youku_Token];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_Youku_Refresh];
    [[NSNotificationCenter defaultCenter] postNotificationName:CZLogoutNotification object:nil];
    
    _currentUser = nil;
    [self.mineTableView reloadData];
    
    self.userIconImageView.image = [UIImage imageNamed:@"logo"];
    self.nickNameLabel.text = @"";
    CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    CZNavigationController *homeNC = rootVC.childViewControllers[0];
    CZMessionCenterViewController *homeVC = homeNC.childViewControllers[0];
    [homeVC setUserIconImage];
    rootVC.selectedIndex = 0;
}

#pragma mark- 下拉放大视图
- (void)setparallaxHeaderView {
    _parallaxHeaderView = [UIImageView new];
    [self.view insertSubview:_parallaxHeaderView belowSubview:_mineTableView];
    _parallaxHeaderView.contentMode = UIViewContentModeScaleAspectFill;
    _parallaxHeaderView.image = [UIImage imageNamed:@"0ff41bd5ad6eddc444593de23fdbb6fd52663368.jpg"];
    [_parallaxHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuideTop);
        _parallaxHeaderHeightConstraint = make.height.equalTo(@(ParallaxHeaderHeight));
    }];
    [_mineTableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark- sectionHeaderView && sectionFooterView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, section == 0 ? 1 : 9)];
    sectionView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    return sectionView;
//    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, section == 4 ? 10 : 1)];
    footView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 4 ? 10 : 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 1 : 9;
}


#pragma mark- NaviBar渐隐效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self setNaviBar];
}

- (void)setNaviBar {
    CGFloat minY = -ParallaxHeaderHeight;
    CGFloat maxY = ParallaxHeaderHeight + 100;
    if (_mineTableView.contentOffset.y >= minY && _mineTableView.contentOffset.y <= maxY) {
        CGFloat alpha = (_mineTableView.contentOffset.y + ParallaxHeaderHeight) / maxY;
        [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:alpha];
        self.navigationController.navigationBar.alpha = alpha;
    } else if(_mineTableView.contentOffset.y <= -minY){
        [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:0];
        self.navigationController.navigationBar.alpha = 0;

    } else {
        [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
        self.navigationController.navigationBar.alpha = 1;

    }
}

#pragma mark- tableViewDataSource tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3 && indexPath.row == 2 && _currentUser && _currentUser.honors.count > 4) {
        return (20 + (_currentUser.honors.count / 5 + 1) * 30);
    }
    return UITableViewAutomaticDimension;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 6;
            break;
        case 3:
            return 3;
            break;
        case 4:
            return 1;
            break;
        default:
            return 0;
            break;
    };
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CZMineCell *cell = (CZMineCell *)[tableView dequeueReusableCellWithIdentifier:mine_cell];
    for (UIView *view in cell.contentView.subviews) {
        if(view.tag == 10000) {
            [view removeFromSuperview];
        };
        if (view.tag > 1999) {
            [view removeFromSuperview];
        }
    }
    NSString *sectionStr = [NSString stringWithFormat:@"%ld", (long)indexPath.section];
    cell.titleLabel.text = self.titleDic[sectionStr][indexPath.row];
    cell.contentLael.font = [UIFont systemFontOfSize:17];
    cell.iconImageView.image = [UIImage imageNamed:self.iconDic[sectionStr][indexPath.row]];
    cell.contentLael.textAlignment = NSTextAlignmentRight;
//    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.vipLabel.hidden = YES;
    cell.vipLabel.layer.cornerRadius = 3;
    cell.vipLabel.clipsToBounds = YES;
    if (_currentUser) {
        switch (indexPath.section) {
            case 0: {
                cell.contentLael.text = _currentUser.phone;
            }
                break;
            case 1: {
                if (indexPath.row == 0) {
                    if (_currentUser.is_member == 0) {
                        // 非会员
                        cell.contentLael.text = @"";
                        cell.vipLabel.hidden = NO;

//                        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
                    } else {
                        // 会员
                        cell.contentLael.font = [UIFont systemFontOfSize:14];
                        cell.iconImageView.image = [UIImage imageNamed:@"my_icon_member"];
                        cell.contentLael.text = [NSString stringWithFormat:@"会员截止：%@", [_currentUser.member_end_date substringToIndex:10]];

                    }
                } else {
                    cell.contentLael.text = _currentUser.nickname;
                }
            }
                break;
            case 2: {
                switch (indexPath.row) {
                    case 0: {
                        cell.contentLael.text = _currentUser.sex == 1 ? @"帅哥" : @"妹子";
                    }
                        break;
                    case 1 : {
                        cell.contentLael.text = [NSString stringWithFormat:@"%ld", (long)_currentUser.age];
                    }
                        break;
                    case 2: {
                        cell.contentLael.text = _currentUser.qq;
                    }
                        break;
                    case 3 : {
                        cell.contentLael.text = _currentUser.guardian_name;
                    }
                        break;
                    case 4 : {
                        cell.contentLael.text = _currentUser.guardian_phone;
                    }
                        break;
                    case 5 : {
                        cell.contentLael.text = _currentUser.default_address[@"address"];
                    }
                        break;
    
                    default:
                        break;
                }
            }
                break;
            case 3: {
                switch (indexPath.row) {
                    case 0:
                        cell.contentLael.text = [NSString stringWithFormat:@"%ld", (long)_currentUser.na_currency];
                        break;
                    case 1 : {
                        
                        UILabel *expLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 15)];
                        expLabel.tag = 10000;
                        expLabel.font = [UIFont systemFontOfSize:15];
                        expLabel.textColor = cell.contentLael.textColor;
                        expLabel.centerY = cell.titleLabel.centerY;
                        expLabel.left = cell.titleLabel.right - 20;
                        expLabel.textAlignment = NSTextAlignmentCenter;
                        if (_currentUser.experience_point  < 750 || _currentUser.experience_point  == 750) {
                            cell.contentLael.text = @"世界移民";
                            expLabel.text = [NSString stringWithFormat:@"%d/750", _currentUser.experience_point];
                        }
                        if (_currentUser.experience_point > 750 || _currentUser.experience_point  == 1550) {
                            cell.contentLael.text = @"流浪猎人";
                            expLabel.text = [NSString stringWithFormat:@"%d/1550", _currentUser.experience_point];

                        }
                        if (_currentUser.experience_point > 1550 || _currentUser.experience_point == 2450) {
                            cell.contentLael.text = @"猎人长";
                            expLabel.text = [NSString stringWithFormat:@"%d/2450", _currentUser.experience_point];

                        }
                        if (_currentUser.experience_point > 2450 || _currentUser.experience_point == 3650) {
                            cell.contentLael.text = @"法师";
                            expLabel.text = [NSString stringWithFormat:@"%d/3650", _currentUser.experience_point];

                        }
                        
                        if (_currentUser.experience_point > 3650 || _currentUser.experience_point == 5350) {
                            cell.contentLael.text = @"祭祀";                            expLabel.text = [NSString stringWithFormat:@"%d/5350", _currentUser.experience_point];

                        }
                        
                        if (_currentUser.experience_point > 5350 || _currentUser.experience_point == 8000) {
                            cell.contentLael.text = @"酋长";
                            expLabel.text = [NSString stringWithFormat:@"%d/8000", _currentUser.experience_point];

                        }
                        
                        [cell.contentView addSubview:expLabel];
//                        UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 15)];
//                        grayView.tag = 10000;
//                        grayView.layer.cornerRadius = 3;
//                        grayView.layer.masksToBounds = YES;
//                        grayView.left = cell.titleLabel.right;
//                        grayView.centerY = cell.contentView.centerY;
//                        grayView.backgroundColor = mRGBColor(230, 230, 230);
//                        [cell.contentView addSubview:grayView];
//                        
//                        CGFloat x = .5f;
//                        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//                        gradientLayer.cornerRadius = 3;
//                        gradientLayer.masksToBounds = YES;
//                        gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)mRGBColor(0, 186, 158).CGColor];
//                        gradientLayer.locations = @[@(-0.2),@0.99, @1.0];
//                        gradientLayer.startPoint = CGPointMake(0, 0);
//                        gradientLayer.endPoint = CGPointMake(1.0, 0);
//                        gradientLayer.frame = CGRectMake(0, 0, x * grayView.width, grayView.height);
//                        [grayView.layer addSublayer:gradientLayer];
                    }
                        break;
                    case 2 :{
                        cell.contentLael.text = @"";
                        UIImageView *lastView;
                        NSDictionary *dic;
                        BOOL newLine = YES;
                        for (int i = 0; i < _currentUser.honors.count; i ++) {
                            dic = _currentUser.honors[i];
                            newLine = i % 5 == 0 ? YES : NO;
                            UIImageView *imageView = [[UIImageView alloc] init];
                            imageView.contentMode = UIViewContentModeScaleToFill;
                            [cell.contentView addSubview:imageView];
                            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                                make.top.equalTo(lastView ? (newLine ? lastView.mas_bottom : lastView): cell.titleLabel).offset(lastView ? (newLine ? 5 : 0) : 0);
                                
                                make.right.equalTo(newLine ? cell.contentLael : lastView.mas_left).offset(newLine ? 0 : -5);
                                make.height.width.equalTo(@25);
                            }];
                            imageView.layer.cornerRadius = 25 / 2.f;
                            imageView.clipsToBounds = YES;
                            imageView.yy_imageURL = [NSURL URLWithString:dic[@"honor_pic"]];
                            lastView = imageView;
                            imageView.tag = 2000 + i;
                        }
                    }
                        break;
                    default:
                        break;
                }
            }
                break;
            case 4: {
                cell.contentLael.text = @"";
            }
                break;
            default:
                break;
        }
    } else {
        cell.contentLael.text = @"";
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 设置地址
    if (indexPath.section == 2 && indexPath.row == 5) {
        CZAddressManagerViewController *addressVC = [[CZAddressManagerViewController alloc] init];
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    // 设置nickname
    CZMultiSettingViewController *settingVC = [[CZMultiSettingViewController alloc] init];
    if (indexPath.section == 1 && indexPath.row == 1) {
        settingVC.changeType = @"nickname";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    // 设置性别
    if (indexPath.section == 2 && indexPath.row == 0) {
        settingVC.changeType = @"sex";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    // 设置年龄
    if (indexPath.section == 2 && indexPath.row == 1) {
        settingVC.changeType = @"age";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    // 设置QQ
    if (indexPath.section == 2 && indexPath.row == 2) {
        settingVC.changeType = @"qq";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    // 设置监护人姓名
    if (indexPath.section == 2 && indexPath.row == 3) {
        settingVC.changeType = @"guardian_name";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    // 设置监护人电话
    if (indexPath.section == 2 && indexPath.row == 4) {
        settingVC.changeType = @"guardian_phone";
        [self.navigationController pushViewController:settingVC animated:YES];
    }
    @weakify(self);
    settingVC.backBlock = ^(BOOL success) {
        if (success) {
            [weak_self getUserData];
        }
    };
    
    // 手机
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:User_Phone];
    if (indexPath.section == 0 && indexPath.row == 0) {
        if (phone && phone.length == 11) {
            CZChangePhoneViewController *addressVC = [[CZChangePhoneViewController alloc] init];
            [self.navigationController pushViewController:addressVC animated:YES];
        } else {
            CZBindMoblieViewController *bindVC = [[CZBindMoblieViewController alloc] init];
            [self.navigationController pushViewController:bindVC animated:YES];
        }
        
    }
    
    //线上报名
    if (indexPath.section == 1 && indexPath.row == 0) {
        CZEnrollViewController *addressVC = [[CZEnrollViewController alloc] init];
        addressVC.vipEndDate = _currentUser.member_end_date;
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    
    // 修改密码
    if (indexPath.section == 4 ) {
        CZChangePWDViewController *addressVC = [[CZChangePWDViewController alloc] init];
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    
}



#pragma mark- 获取用户数据
- (void)getUserData {
    
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-info/get-info",APP_HOST];
    @weakify(self);
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        return;
    }
    
    [SVProgressHUD showWithStatus:@"获取个人数据中..."];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]} success:^(NSDictionary *response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            _currentUser = [[CZUserModel alloc] init];
            [_currentUser setValuesForKeysWithDictionary:response[@"result"]];
            self.nickNameLabel.text = _currentUser.nickname;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weak_self.mineTableView reloadData];
            });
        } else if ([response[@"status"] isEqualToString:@"104"]) {
            CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            CZNavigationController *naviVC = rootVC.childViewControllers[0];
            CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
            CZNavigationController *mineNC = rootVC.childViewControllers[4];
            CZMineViewController *mineVC = mineNC.childViewControllers[0];
            CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self.parentViewController];
            @weakify(mineVC);
            loginVC.callBack = ^(){
                [weak_mineVC getUserData];
                [homeVC setUserIconImage];
                weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
                [self getUserData];
            };
            return;
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

#pragma mark- 上传头像到服务器
- (void)updateUserIconWithURLString:(NSString *)URLString image:(UIImage *)image {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user-info/update-info",APP_HOST];
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"logo" : URLString} success:^(id response) {
        if([response[@"code"] isEqualToString:@"200"]){
            [SVProgressHUD showSuccessWithStatus:@"上传头像成功"];
            [[NSUserDefaults standardUserDefaults] setObject:URLString forKey:User_Logo];
            self.userIconImageView.image = image;
            CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            CZNavigationController *naviVC = rootVC.childViewControllers[0];
            CZMessionCenterViewController *homeVC = naviVC.childViewControllers[0];
            [homeVC setUserIconImage];
            
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

#pragma mark- 观察者
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint contentOffset = ((NSValue *)change[NSKeyValueChangeNewKey]).CGPointValue;
        if (contentOffset.y < -ParallaxHeaderHeight) {
            _parallaxHeaderHeightConstraint.equalTo(@(-contentOffset.y));
        }
        
    }
}



- (void)dealloc {
    [_mineTableView removeObserver:self forKeyPath:@"contentOffset"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
